package com.etoc.test.activemq;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.sql.DataSource;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.etoc.flow.dto.ApiOrderExtendDto;
import com.etoc.flow.dto.OrderDetailDto;

import net.sf.json.JSONObject;

public class Sender {

    public static void main(String[] args) {
        // ConnectionFactory ：连接工厂，JMS 用它创建连接
        ConnectionFactory connectionFactory;
        // Connection ：JMS 客户端到JMS Provider 的连接
        Connection connection = null;
        // Session： 一个发送或接收消息的线程
        Session session;
        // Destination ：消息的目的地;消息发送给谁.
        Destination destination;
        // MessageProducer：消息发送者
        MessageProducer producer;
        // TextMessage message;
        // 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
        connectionFactory = new ActiveMQConnectionFactory(
                "etoc",
                "etoc@password",
                "tcp://localhost:61616");
        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);
            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置
            destination = session.createQueue("messageQueue");
            // 得到消息生成者【发送者】
            producer = session.createProducer(destination);
            // 设置不持久化，此处学习，实际根据项目决定
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            // 构造消息，此处写死，项目就是参数，或者方法获取
            sendMessage(session, producer);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }

    public static void sendMessage(Session session, MessageProducer producer)
            throws Exception {
    	List<OrderDetailDto> datas = getDatas();
    	if (CollectionUtils.isNotEmpty(datas)) {
			for (OrderDetailDto orderDetailDto : datas) {
				JSONObject jsonObject = JSONObject.fromObject(orderDetailDto);
				String json = jsonObject.toString();
	            TextMessage message = session.createTextMessage(json);
	            // 发送消息到目的地方
	            System.out.println("发送消息：" + "ActiveMq 发送的消息" + message);
	            producer.send(message);
			}
		}
    }
    
	public static DataSource getDataSource() {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUrl("jdbc:mysql://113.57.230.6:10010/channel_order");
		ds.setUsername("root");
		ds.setPassword("etoc@123");
		ds.setMaxTotal(100);// 连接池的最大数据库连接数。设为0表示无限制
		ds.setInitialSize(5);// 初始化连接数量
		ds.setMaxWaitMillis(60000);//  最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制
		ds.setMaxIdle(100);// 最大等待连接中的数量,设 0 为没有限制
		ds.setMinIdle(5);// 最小等待连接中的数量,设 0 为没有限制
		ds.setRemoveAbandonedOnBorrow(true);// 强制自我中断避免dbcp自身bug出现连接过久资源耗尽
		ds.setRemoveAbandonedTimeout(180);// 自我中断时间秒
		return ds;
	}
	
    public static List<OrderDetailDto> getDatas() {
    	String sql = "select * from api_order_info a where a.sequence_id=?";
    			/*"select a.sequence_id,a.service_id,a.order_way_id,a.order_id,a.phone,a.area_id,a.mobile_operator,a.channel_id,a.product_no,a.trans_no,a.clean_time,"
    			+ "e.isp_id,e.largess_id,e.isp_code,e.order_code,e.order_time,e.order_id order_id_extend,e.order_no "
    			+ "from channel_order.api_order_info a "
    			+ "join channel_order.api_order_extend_info e on a.sequence_id=e.api_order_info_id "
    			+ "where 1=1 and a.sequence_id=? "
    			+ "order by a.order_id desc, e.order_no  limit 10";*/
    	String id = "2192d79da3074a61891f439685d28772";
    	QueryRunner qr = new QueryRunner(getDataSource());
    	List<OrderDetailDto> datas = null;
    	try {
    		BeanProcessor generousBeanProcessor = new GenerousBeanProcessor();
			datas = qr.query(sql, new BeanListHandler<>(OrderDetailDto.class, new BasicRowProcessor(generousBeanProcessor)), id);
			sql = "select * from api_order_extend_info e where e.api_order_info_id=? order by e.order_no";
			if (CollectionUtils.isNotEmpty(datas)) {
				Map<String, String> columnPropertyMap = new HashMap<>();
				columnPropertyMap.put("id", "id");
				columnPropertyMap.put("api_order_info_id", "apiOrderInfoId");
				columnPropertyMap.put("order_id", "orderId");
				columnPropertyMap.put("isp_id", "ispId");
				columnPropertyMap.put("largess_id", "largessId");
				columnPropertyMap.put("isp_code", "ispCode");
				columnPropertyMap.put("order_code", "orderCode");
				columnPropertyMap.put("create_time", "createTime");
				columnPropertyMap.put("order_time", "orderTime");
				columnPropertyMap.put("order_no", "order");
				BeanProcessor beanProcessor = new BeanProcessor(columnPropertyMap);
				for (OrderDetailDto orderDetailDto : datas) {
					List<ApiOrderExtendDto> apiOrderExtendDtos = qr.query(sql, new BeanListHandler<>(ApiOrderExtendDto.class, new BasicRowProcessor(beanProcessor)), orderDetailDto.getSequenceId());
					orderDetailDto.setApiOrderExtendlist(apiOrderExtendDtos);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	
    	return datas;
    }
}
